package com.leyou.goods.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;

@Service
public class GoodsHtmlService {
    @Autowired
    private TemplateEngine engine;//页面静态化的类
    @Autowired
    private GoodsService goodsService;

    /**
     * 创建静态文件
     * @param spuId
     */
    public void createHtml(Long spuId){
        //初始化上下文
        Context context = new Context();
        //在上下文中添加数据模型
        context.setVariables(goodsService.loadData(spuId));
        PrintWriter printWriter =null;
        try {
            //初始化输出流,输出到本地
            File file = new File("E:\\nginx-1.14.0\\nginx-1.14.0\\html\\item\\" + spuId + ".html");
            printWriter = new PrintWriter(file);
            engine.process("item",context,printWriter);
        }catch (Exception e){

        }finally {
            if(printWriter!=null){
                printWriter.close();
            }
        }
    }

    /**
     * 删除静态文件
     * @param id
     */
    public void deleteHtml(Long id) {
        File file = new File("E:\\nginx-1.14.0\\nginx-1.14.0\\html\\item\\" + id + ".html");
        file.deleteOnExit();
    }
}
